<script setup lang="ts">
//@ts-ignore
import type { UploadProps } from 'element-plus'
//@ts-ignore
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import {
  reqHasTrade,
  reqAddTrade,
  reqEditTrade,
  reqDelTrade,
} from '@/api/product/trademark'
import {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type.ts'
const pageNo = ref<number>(1)
const pageSize4 = ref<number>(3)
const total = ref<number>(3)
const tradeArray = ref<Records>([])
const tradeInfo = ref<TradeMark>({
  id: 0,
  tmName: '',
  logoUrl: '',
})
const title = ref('')
const formref = ref()
//请求页面信息并更新数据数组
const reqpage = async () => {
  const p: TradeMarkResponseData = await reqHasTrade(
    pageNo.value,
    pageSize4.value,
  )
  total.value = p.data.total
  tradeArray.value = p.data.records
}
onMounted(() => {
  reqpage()
})
//改变分页器页数触发
const changepageNo = () => {
  reqpage()
}
//改变分页器每一页个数触发
const changesize = () => {
  pageNo.value = 1
  reqpage()
}

const isShow = ref(false)
//添加品牌
const addTrademark = () => {
  isShow.value = true
  title.value = '添加品牌'
  tradeInfo.value.logoUrl = ''
  tradeInfo.value.tmName = ''
  formref.value?.clearValidate('logoUrl')
  formref.value?.clearValidate('tmName')
}
const cancel = () => {
  isShow.value = false
}
//确认按钮触发
const dialogFormVisible = async () => {
  formref.value.validate(async (vaild: any) => {
    if (vaild) {
      isShow.value = false
      if (title.value === '添加品牌') {
        const p = await reqAddTrade(
          tradeInfo.value.tmName,
          tradeInfo.value.logoUrl,
        )
        reqpage()
        if (p.code === 200) {
          ElMessage({
            type: 'success',
            message: '添加成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: p.data,
          })
        }
      } else if (title.value === '修改品牌') {
        const p = await reqEditTrade(
          tradeInfo.value.id as number,
          tradeInfo.value.tmName,
          tradeInfo.value.logoUrl,
        )
        reqpage()
        if (p.code === 200) {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: p.data,
          })
        }
      }
    } else {
      ElMessage.warning('请完善表单信息')
    }
  })
}
//图片上传前触发的钩子，进行文件验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage({
      type: 'error',
      message: '请选择合适的文件格式！',
    })
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片大小不得超过5MB!')
    return false
  }
  return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any) => {
  tradeInfo.value.logoUrl = response.data
  formref.value.clearValidate('logoUrl')
}
const edit = async (row: any) => {
  isShow.value = true
  title.value = '修改品牌'
  tradeInfo.value.id = row.id
  tradeInfo.value.tmName = row.tmName
  tradeInfo.value.logoUrl = row.logoUrl
  formref.value?.clearValidate('logoUrl')
  formref.value?.clearValidate('tmName')
  // await reqEditTrade(tradeInfo.value.id,tradeInfo.value.tmName,tradeInfo.value.logoUrl)
}
const deltrade = async (id: number) => {
  const p = await reqDelTrade(id)
  reqpage()
  if (p.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: p.data,
    })
  }
}
const validatePass = (_:any, value: any, callback: any) => {
  if (value) callback()
  else callback(new Error('请选择图片上传'))
}
const rules = {
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { max: 10, min: 2, message: '品牌名称为2~10个字符', trigger: 'blur' },
  ],
  logoUrl: [
    { required: true, message: '请选择图片上传' },
    { validator: validatePass, message: '请选择图片上传', trigger: 'blur' },
  ],
}
</script>

<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="plus" @click="addTrademark" v-has="'btn.Trademark.add'">
      添加品牌
    </el-button>
    <el-table style="margin: 10px 0px" border :data="tradeArray">
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row }">
          <el-button
            type="warning"
            size="small"
            icon="Edit"
            @click="edit(row)"
            v-has="'btn.Trademark.update'"
          ></el-button>
          <el-popconfirm title="确认删除吗？" @confirm="deltrade(row.id)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete" v-has="'btn.Trademark.remove'"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize4"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @current-change="changepageNo"
      @size-change="changesize"
    />
  </el-card>
  <el-dialog v-model="isShow" :title="title" width="500">
    <el-form :model="tradeInfo" :rules="rules" ref="formref">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          style="width: 80%"
          v-model="tradeInfo.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="tradeInfo.logoUrl"
            :src="tradeInfo.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
